//
//  JHJTabBarController.m
//  项目
//
//  Created by dllo on 16/5/8.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "JHJTabBarController.h"
#import "JHJTabBarCollectionViewCell.h"
#import "STKAudioPlayer.h"
#import "STKAudioPlayerHandle.h"
#import "AuditionListModel.h"
#import "PosterDetailSongsModel.h"
#import "MusicDetailsViewController.h"
#import "DataHandle.h"

@interface JHJTabBarController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong)NSArray *songsArr;
@property (nonatomic, strong)NSIndexPath *indexPath;

@property (nonatomic, strong)STKAudioPlayer *audioPlayer;
@property (nonatomic, strong)STKAudioPlayerHandle *audioPlayerHandle;
@property (nonatomic, strong)NSMutableArray *mutableArray;
@property (nonatomic, assign)NSInteger currentOfMusic;// 当前播放音乐的位置.
@property (nonatomic, strong)NSTimer *timer;
@property (nonatomic, strong)NSMutableArray *dbArray;
@property (nonatomic, assign)BOOL first;
@property (nonatomic, retain)UICollectionView *collectionView;

@end

@implementation JHJTabBarController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tabBar removeFromSuperview];
    self.audioPlayer = [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] audioPlayer];
    [self creatView];
    [[DataHandle shareDataBaseHandle] openDB];
    self.dbArray = [NSMutableArray array];
    [self addObserver:self forKeyPath:@"mutableArray" options:NSKeyValueChangeNewKey || NSKeyValueChangeOldKey context:nil];
    [self searchdataBase];
}

- (void)searchdataBase {
    [[DataHandle shareDataBaseHandle] createTableWithName:@"tabBarTable"];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        
        self.dbArray = [NSMutableArray arrayWithArray:[[DataHandle shareDataBaseHandle] selectPosterSongsModelFromTable:@"tabBarTable"]];
        
       dispatch_async(dispatch_get_main_queue(), ^{
           
           [self.collectionView reloadData];
           STKAudioPlayerHandle *stk = [STKAudioPlayerHandle shareSTKAudioPlayerHandle];
           stk.mutableArray = [NSMutableArray arrayWithArray:self.dbArray];
//           self.audioPlayerHandle.mutableArray = self.dbArray;
           for (PosterDetailSongsModel *model in self.dbArray) {
//               NSLog(@"%@",model.picUrl);
               
           }
       });
//        for (PosterDetailSongsModel *model in self.dbArray) {
//
//        }
        
    });
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"mutableArray"]) {
//        NSLog(@"111");
//        if (self.mutableArray.count != 0) {
////            [[DataHandle shareDataBaseHandle] dropTable:@"tabBarTable"];
////            [[DataHandle shareDataBaseHandle] dropTable:@"tabBarTable"];
////            for (PosterDetailSongsModel *model in self.mutableArray) {
////                [[DataHandle shareDataBaseHandle] insertPosterSongsModel:model initoTable:@"tabBarTable"];
//            }
//        }
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            static dispatch_once_t onceToken;
            dispatch_once(&onceToken, ^{
                NSLog(@"11111111111");
                [[DataHandle shareDataBaseHandle] dropTable:@"tabBarTable"];
                [[DataHandle shareDataBaseHandle] createTableWithName:@"tabBarTable"];
                [[DataHandle shareDataBaseHandle] insertMany:self.mutableArray intoTable:@"tabBarTable"];
            });
        });
    }
}

- (void)creatView {
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, HEIGHT - 100, WIDTH, 100)];
    [self.view addSubview:contentView];
    contentView.tag = 1000;
    contentView.backgroundColor = [UIColor whiteColor];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(WIDTH - 20, 80);
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    flowLayout.minimumInteritemSpacing = 20;
    flowLayout.minimumLineSpacing = 20;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 100) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [contentView addSubview:self.collectionView];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[JHJTabBarCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    self.collectionView.pagingEnabled = YES;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getCurrentIndexPath:) name:@"playMusic" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getSongs:) name:@"HandelArr" object:nil];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 100)];
    UIImage *image1 = [UIImage imageNamed:@"jhj2"];
    UIImage *image2 = [UIImage imageNamed:@"jhj1"];
    imageView.dk_imagePicker = [DKImage pickerWithNormalImage:image1 nightImage:image2];
//    DKImagePickerWithNames(@"jhj2",@"jhj1",@"jhj3",@"jhj4");
    self.collectionView.backgroundView = imageView;
//    self.collectionView
}

// tabBar隐藏或者出现.

- (void)hiddenTabBarWithAnimation:(BOOL)animation {
    
    UIView *view = [self.view viewWithTag:1000];
    if (animation) {
        [UIView animateWithDuration:0.5 animations:^{
            view.frame = CGRectMake(0, HEIGHT, WIDTH, 100);
            
        } completion:^(BOOL finished) {
            
            
        }];
    } else {
        
        [UIView animateWithDuration:0 animations:^{
            view.frame = CGRectMake(0, HEIGHT, WIDTH, 100);
            
        } completion:^(BOOL finished) {
            
            
        }];

    }
    
    
}

- (void)showTabBarWithAnimation:(BOOL)animation {
    UIView *view = [self.view viewWithTag:1000];
    if (animation) {
        [UIView animateWithDuration:0.5 animations:^{
            view.frame = CGRectMake(0, HEIGHT - 100, WIDTH, 100);
            
        } completion:^(BOOL finished) {
            
            
        }];
    } else {
        
        [UIView animateWithDuration:0 animations:^{
            view.frame = CGRectMake(0, HEIGHT - 100, WIDTH, 100);
            
        } completion:^(BOOL finished) {

            
        }];
    }
}

- (void)getSongs:(NSNotification *)noti {
    self.mutableArray = [noti object];
//    NSLog(@"%ld",self.mutableArray.count);
    [self.collectionView reloadData];
}

- (void)getCurrentIndexPath:(NSNotification *)noti {
    self.indexPath = [noti object];
    self.currentOfMusic = self.indexPath.row;
    self.audioPlayerHandle = [STKAudioPlayerHandle shareSTKAudioPlayerHandle];
    self.audioPlayer = [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] audioPlayer];
    self.audioPlayerHandle.audioPlayerStyle = [[[NSUserDefaults standardUserDefaults] valueForKey:@"audioPlayerStyle"] integerValue];
    [self.collectionView scrollToItemAtIndexPath:self.indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.mutableArray.count == 0) {
        return self.dbArray.count;
    } else {
        return self.mutableArray.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    JHJTabBarCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
//    JHJTabBarModel *model = [[JHJTabBarModel alloc] init];
//    model.image = [UIImage imageNamed:@"smiley_26"];
//    model.image = [UIImage imageNamed:@"21003319221463329082_4-1.jpg"];
//    cell.model = model;
//    cell.isPlay = YES;
    if (self.mutableArray.count == 0) {
        cell.songsModel = self.dbArray[indexPath.row];
        
    } else {
        cell.songsModel = self.mutableArray[indexPath.row];
    }
    cell.cellBlock = ^(BOOL isPlay) {
        [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] pauseOrResumePlayer];
    };
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    MusicDetailsViewController *musicVC = [[MusicDetailsViewController alloc] initWithNibName:@"MusicDetailsViewController" bundle:[NSBundle mainBundle]];
    if (self.mutableArray != 0) {
        musicVC.array = self.mutableArray;
        //    NSLog(@"%@",self.mutableArray);
        NSLog(@"1111111111111111111");
        musicVC.currentOfMusic = indexPath.row;
    } else {
        musicVC.array = self.dbArray;
        NSLog(@"skaldfjklsdjfsdklfsdklfjds");
        //    NSLog(@"%@",self.mutableArray);
        musicVC.currentOfMusic = indexPath.row;

    }
    
    [self presentViewController:musicVC animated:YES completion:^{
        
        
        
    }];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] nextSonger];
    [scrollView setContentOffset:CGPointMake(WIDTH * [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] currentOfMusic], 0) animated:NO];
   JHJTabBarCollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:[[STKAudioPlayerHandle shareSTKAudioPlayerHandle] currentOfMusic] inSection:0]];
    [cell rotation];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
